package cn.shanke.torrentmanagerserver.controller;

import cn.shanke.torrentmanagerserver.controller.common.ResponseModel;
import cn.shanke.torrentmanagerserver.service.ConfigService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Resource
    private ConfigService configService;

    @GetMapping("/listFolders")
    public ResponseModel listFolders(@RequestParam String path) {
        if (StringUtils.hasText(path)) {
            path = configService.getCurrent().getManagePath();
        }
        File parent = new File(configService.toRealPath(path));
        if (parent.exists()) {
            File[] children = parent.listFiles(pathname -> pathname.isDirectory());
            return ResponseModel.success().data(
                    Arrays.stream(children).map(file -> {
                        JSONObject child = new JSONObject();
                        child.put("title", file.getName());
                        child.put("key", configService.toVisualPath(file.getAbsolutePath()));

                        return child;
                    }).collect(Collectors.toList())
            );
        }
        return ResponseModel.success().data(Collections.emptyList());
    }

//    public static void main(String[] args) {
//        Path root = Paths.get("N:\\video\\tv");
//        System.out.println(root.toFile().getName());
//        System.out.println(root.getRoot().toFile().getName());
//        System.out.println(root.getNameCount());
//        root.iterator().forEachRemaining(path -> System.out.println(path.toFile().getName()));
//    }
}
